package com.xinghai.system.service.impl;


import java.rmi.ServerException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.xinghai.system.domain.QdUser;
import com.xinghai.system.domain.QdUserPointsLog;
import com.xinghai.system.domain.entity.RechargePointsDTO;
import com.xinghai.system.service.IQdUserPointsLogService;
import com.xinghai.system.service.IQdUserService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.xinghai.common.constant.GenConstants;
import com.xinghai.system.mapper.QdUserWalletMapper;
import com.xinghai.system.domain.QdUserWallet;
import com.xinghai.system.service.IQdUserWalletService;

/**
 * 用户钱包Service业务层处理
 *
 * @author xinghai
 * @date 2024-12-04
 */
@Service
public class QdUserWalletServiceImpl extends ServiceImpl<QdUserWalletMapper, QdUserWallet>
        implements IQdUserWalletService
{

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private IQdUserService qdUserService;

    @Autowired
    private IQdUserPointsLogService userPointsLogService;
    /**
     * 查询用户钱包列表
     *
     * @param qdUserWallet 用户钱包
     * @return 用户钱包集合
     */
    @Override
    public List<QdUserWallet> list(QdUserWallet qdUserWallet) {
        QueryWrapper<QdUserWallet> queryWrapper = new QueryWrapper<>();
        if (qdUserWallet.getStatus()!= null  && !qdUserWallet.getStatus().isEmpty()){
            queryWrapper.eq("status", qdUserWallet.getStatus());
        }
        if (qdUserWallet.getParams().get("beginCreateTime")!= null && !"".equals(qdUserWallet.getParams().get("beginCreateTime"))
        &&qdUserWallet.getParams().get("endCreateTime")!= null && !"".equals(qdUserWallet.getParams().get("endCreateTime"))){
            queryWrapper.between("create_time", qdUserWallet.getParams().get("beginCreateTime"),qdUserWallet.getParams().get("endCreateTime"));
        }
        if (qdUserWallet.getUserPhone()!= null  && !qdUserWallet.getUserPhone().isEmpty()){
            queryWrapper.like("user_phone", qdUserWallet.getUserPhone());
        }
        if (qdUserWallet.getUserName()!= null  && !qdUserWallet.getUserName().isEmpty()){
            queryWrapper.like("user_name", qdUserWallet.getUserName());
        }
        if (qdUserWallet.getUserId()!= null){
            queryWrapper.eq("user_id", qdUserWallet.getUserId());
        }
        if (qdUserWallet.getUserIds()!= null && !qdUserWallet.getUserIds().isEmpty()){
            //queryWrapper.apply("FIND_IN_SET(user_id,get_child_list('"+qdUserWallet.getUserIds()+"'))");
            queryWrapper.apply("FIND_IN_SET(user_id,'"+qdUserWallet.getUserIds()+"')");
        }
        return this.list(queryWrapper);
    }


    /**
     * 删除用户钱包信息
     * @param id 需要删除的数据ID
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    public boolean delete(Long id, boolean flag) {
        if (flag){
            QdUserWallet qdUserWallet = new QdUserWallet();
            qdUserWallet.setId(id);
            qdUserWallet.setDelFlag(GenConstants.DELETE_FLAG_YES);
            return this.updateById(qdUserWallet);
        }
        return this.removeById(id);
    }

    /**
     * 批量删除用户钱包信息
     *
     * @param ids 需要删除的数据ID集合
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteBatch(Long[] ids, boolean flag) {
        if (flag){
            List<QdUserWallet> collect = Arrays.stream(ids).map(m -> {
                QdUserWallet qdUserWallet = new QdUserWallet();
                qdUserWallet.setId(m);
                qdUserWallet.setDelFlag(GenConstants.DELETE_FLAG_YES);
                return qdUserWallet;
            }).collect(Collectors.toList());
            return this.updateBatchById(collect);
        }
        return this.removeByIds(Arrays.asList(ids));
    }

    /**
     * 导入用户钱包信息
     *
     * @param list 用户钱包信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<QdUserWallet> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            QdUserWalletMapper qdUserWalletMapper = sqlSession.getMapper(QdUserWalletMapper.class);
            list.forEach(qdUserWalletMapper::insert);
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    public QdUserWallet getByUserId(String loginId) {
        QueryWrapper<QdUserWallet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",loginId);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public QdUserWallet checkWallet(String loginId) throws ServerException {
        QdUserWallet wallet = this.getByUserId(loginId);
        //没有就创建
        if(wallet==null){
            QdUser user = qdUserService.getByLoginId(loginId);
            if (user==null){
                throw new ServerException("用户不存在");
            }
            wallet = new QdUserWallet();
            wallet.setUserId(user.getId());
            wallet.setUserPhone(user.getUserPhone());
            wallet.setUserName(user.getNickName());
            this.baseMapper.insert(wallet);
            wallet = this.baseMapper.selectById(wallet.getId());
        }
        return wallet;
    }

    @Override
    public boolean income(String loginId) {
        return false;
    }

    @Override
    @Transactional
    public int rechargePoints(RechargePointsDTO dto) {
        QdUserWallet w = this.getByUserId(dto.getUserId());
        w.setPoints(w.getPoints().add(dto.getPoints()));
        //记录积分日志
        QdUserPointsLog userPointsLog = new QdUserPointsLog();
        userPointsLog.setUserId(Long.valueOf(dto.getUserId()));
        userPointsLog.setUserPhone(w.getUserPhone());
        userPointsLog.setChangePoints(dto.getPoints());
        userPointsLog.setType(dto.getType());
        userPointsLog.setDetail(dto.getDetail());
        userPointsLog.setUserPhone(w.getUserPhone());
        userPointsLogService.save(userPointsLog);
        return baseMapper.updateById(w);
    }
}
